/* 
 *  Controller.m 
 *  iCPU
 *
 *  Created by Kosovan Sasha
 *  Licensed under GNU GPL v2
 *
 */

#import "Controller.h"
#import "ChatWindowController.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import "cpu.h"

@implementation Controller

- (void)awakeFromNib
{
	//NSLog(@"Awake from nib");
	
	NSStatusBar *bar = [NSStatusBar systemStatusBar];
	//[barItem alloc];
	barItem = [bar statusItemWithLength:NSVariableStatusItemLength];
    [barItem retain];
	[barItem  setImage: [NSImage imageNamed: @"icpu small.png"]];
	//  [theItem setTitle: NSLocalizedString(@"Tablet",@"")];
    [barItem setHighlightMode:YES];
    [barItem setMenu:barMenu];
	
	socketPort = [[NSSocketPort alloc] initWithTCPPort:1025];
	
	//ipfw add divert 10230 all from any to me 1023
    listeningSocket = [[NSFileHandle alloc]
                         initWithFileDescriptor:[socketPort socket]];
	[listeningSocket acceptConnectionInBackgroundAndNotify];
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc addObserver:self 
		   selector:@selector(acceptConnection:)
			   name:NSFileHandleConnectionAcceptedNotification
			 object:listeningSocket];
}

- (void)acceptConnection:(NSNotification *)notification
{
	//NSLog(@"connection accepted");
	NSFileHandle * incomingConnection = [[notification userInfo] objectForKey:NSFileHandleNotificationFileHandleItem];
	ChatWindowController *chatWC;
	
	if ([NSApp respondsToSelector:@selector(requestUserAttention:)]) {
		[NSApp requestUserAttention:NSCriticalRequest];}

    chatWC = [[ChatWindowController alloc] initWithConnection:incomingConnection ];
    [chatWC showWindow:nil];
	[ipWindow close];
	[[notification object] acceptConnectionInBackgroundAndNotify];
}

- (IBAction)call:(id)sender
{
	NSString * logString;
	//struct hostent * hostentry;
	//hostentry = gethostbyname([[ipBox stringValue] cString]);
	 NSHost *host = [NSHost hostWithName:[ipBox stringValue]];
	 
	logString = [[NSString alloc] initWithFormat:@"Calling %@...", [host address]];
	//logString = [[NSString alloc] initWithFormat:@"Calling %@...", [[NSString alloc] initWithCString: hostentry->h_name]];
	[drawer toggle: self];
	[progress startAnimation:self];
//	
	NSLog(logString);
	[NSThread detachNewThreadSelector:@selector(tryToConnect:) toTarget:self withObject:nil];
	
	/*struct sockaddr_in addr;
	struct timeval tv={10,0}; 
	int sockfd = socket( AF_INET, SOCK_STREAM, 0 );
	bzero( &addr, sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons( 1023 );
	inet_pton(AF_INET , [[ipBox stringValue] cString], &addr.sin_addr );
	
	if ( connect( sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
		//NSLog(@"error connectting to socket");
		return;
	   }
	
	if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0){
		//NSLog(@"error setting up socket");
	}
	if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0){
        //NSLog(@"Not answering");
		return ;
    }
	
	struct cpu_packet *cpu_b;
	
	NSFileHandle * fileHandle =  [[[NSFileHandle alloc] initWithFileDescriptor:sockfd ] autorelease];
	NSData  *packet; 
	packet = [[NSData alloc] initWithData:[fileHandle readDataOfLength:16]];
	(struct cpu_packet *)cpu_b = (struct cpu_packet *) [packet bytes];
	
	 NSString * logString2;
	 logString2 = [[NSString alloc] initWithFormat:@"got %i bytes", [packet length]];
	 //NSLog(logString2);	
			 
	NSString * logString3;
		logString3 = [[NSString alloc] initWithFormat:@"Step 3 failed, state=%i, msg=%i, wparam=%i lparam=%i cpu_packet size=%i...", 
						cpu_b->state, cpu_b->msg, cpu_b->wparam, cpu_b->lparam,  sizeof(struct cpu_packet)  ];
			//NSLog(logString3);

	// Open a window with a connection to the remote client.
    ChatWindowController *chatWC;
    chatWC = [[ChatWindowController alloc] initWithConnection: fileHandle];
    [chatWC showWindow:nil];
	[ipWindow close];
	*/
}

- (IBAction)newChat:(id)sender
{
	//[ipWindow makeCurrentContext];
	[ipWindow makeKeyAndOrderFront:self];
}

- (IBAction)showAbout:(id)sender
{
	[aboutWindow makeKeyAndOrderFront: self];
}

- (void) dealloc {
	[barItem release];
	barItem = nil;
	[super dealloc];
}
- (void) tryToConnect: (id) anObject
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSLog(@"New thread");
//	currentThread = [NSThread currentThread];
//	currentPool = pool;
	
//	while ( YES) {
//	    [self stepAnimation:nil];
//		[self setNeedsDisplay:YES];
//		[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.04]];
//	}
	 NSHost *host = [NSHost hostWithName:[ipBox stringValue]];
	struct sockaddr_in addr;
	struct timeval tv={1,0}; 
	int sockfd = socket( AF_INET, SOCK_STREAM, 0 );
	bzero( &addr, sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons( 1023 );
	//
	//struct hostent * hostentry;
	//hostentry = gethostbyname([[ipBox stringValue] cString]);
//	hostentry->
	//
	inet_pton(AF_INET , [[host address] cString], &addr.sin_addr );
	if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0){
		NSLog(@"error setting up socket");
		[pool release];
		[NSThread exit];
	}
	if ( connect( sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0 ) {
		NSLog(@"error connectting to socket");
	//	[drawer toggle:self];
	//	[progress stopAnimation:self]; 
		[pool release];
		[NSThread exit];
		return;
	   }
	
	
	if(setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0){
        NSLog(@"Not answering");
		[pool release];
		[NSThread exit];
		return ;
    }
	
	struct cpu_packet *cpu_b;
	
	NSFileHandle * fileHandle =  [[[NSFileHandle alloc] initWithFileDescriptor:sockfd ] autorelease];
	NSData  *packet; 
	packet = [[NSData alloc] initWithData:[fileHandle readDataOfLength:16]];
	(struct cpu_packet *)cpu_b = (struct cpu_packet *) [packet bytes];
	
	NSString * logString2;
	logString2 = [[NSString alloc] initWithFormat:@"got %i bytes", [packet length]];
	//NSLog(logString2);	
			 
	NSString * logString3;
	logString3 = [[NSString alloc] initWithFormat:@"Step 3 failed, state=%i, msg=%i, wparam=%i lparam=%i cpu_packet size=%i...", 
		cpu_b->state, cpu_b->msg, cpu_b->wparam, cpu_b->lparam,  sizeof(struct cpu_packet)  ];
	//NSLog(logString3);
	[drawer close: self];
	[progress stopAnimation:self]; 
	// Open a window with a connection to the remote client.
    ChatWindowController *chatWC;
    chatWC = [[ChatWindowController alloc] initWithConnection: fileHandle];
    [chatWC showWindow:nil];
	[ipWindow close];
	
	[pool release];
	[NSThread exit];
}
- (IBAction)stop:(id)sender
{
	NSLog(@"Stop");
	[drawer toggle:self];
	[progress stopAnimation:self]; 
	
//	if (currentThread)
//	{
//		[currentPool release];
//		[currentThread finalize];
//	}
		
}
@end
